package com.hippoDocker.payment.controller;

import com.hippoDocker.commons.entities.CommonResult;
import com.hippoDocker.commons.entities.Payment;
import com.hippoDocker.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PaymentController
 * @Description TODO 支付订单控制类
 * @Author hippoDocker
 * @Date 2022/5/30 1:04
 **/
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/createPayment")
    public CommonResult createPayment(@RequestBody Payment payment) {
        int num = paymentService.createPayment(payment);
        log.info("****插入结果：" + num);
        if (num > 0) {
            return new CommonResult(200, "插入成功！"+serverPort, num);
        } else {
            return new CommonResult(444, "插入失败！", null);
        }
    }

    @GetMapping("/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("****查询结果：" + payment);
        if (payment == null) {
            return new CommonResult(444, "查询失败！"+serverPort, null);
        } else {
            return new CommonResult(200, "查询成功！"+serverPort, payment);

        }
    }

    @GetMapping("/lb")
    public String getPaymentLb(){
        return serverPort;
    }

    @GetMapping("/discovery")
    public Object discovery() {
        //获取所有的服务
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("******service:" + service);
        }

        //获取某个服务的所有实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance serviceInstance : instances) {
            log.info(serviceInstance.getServiceId() + "\t" + serviceInstance.getHost() + "\t" + serviceInstance.getPort() + "\t" + serviceInstance.getUri());
        }
        return services;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeOut(){
        //暂停几秒
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/zipkin")
    public  String paymentZipkin(){
        return "hi.i'm paymentzipkin server fall back，welcome to hippoDocker， o(n_∩)o哈哈~~";
    }
}
